<template>
  <div class="search-filters">
    <el-form :model="filterForm" label-width="100px" size="small">
      <!-- 基础搜索选项 -->
      <div class="filter-section" v-if="searchType !== 'advanced'">
        <h4>搜索选项</h4>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="区分大小写">
              <el-switch
                v-model="localOptions.caseSensitive"
                @change="handleOptionsChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="精确匹配">
              <el-switch
                v-model="localOptions.exactMatch"
                @change="handleOptionsChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最大结果数">
              <el-input-number
                v-model="localOptions.maxResults"
                :min="10"
                :max="10000"
                :step="50"
                @change="handleOptionsChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 内容搜索特有选项 -->
      <div class="filter-section" v-if="searchType === 'content'">
        <h4>内容搜索选项</h4>
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="正则表达式">
              <el-switch
                v-model="localContentOptions.regex"
                @change="handleContentOptionsChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="上下文行数">
              <el-input-number
                v-model="localContentOptions.contextLines"
                :min="0"
                :max="10"
                @change="handleContentOptionsChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 高级搜索选项 -->
      <div class="filter-section" v-if="searchType === 'advanced'">
        <h4>高级搜索条件</h4>
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="文件名">
              <el-input
                v-model="localAdvancedCriteria.fileName"
                placeholder="支持通配符 *.vue"
                @input="handleAdvancedCriteriaChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件内容">
              <el-input
                v-model="localAdvancedCriteria.content"
                placeholder="搜索文件内容"
                @input="handleAdvancedCriteriaChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="16">
          <el-col :span="8">
            <el-form-item label="文件类型">
              <el-select
                v-model="localAdvancedCriteria.fileType"
                placeholder="选择文件类型"
                clearable
                @change="handleAdvancedCriteriaChange"
              >
                <el-option label="Vue 组件" value="vue" />
                <el-option label="TypeScript" value="ts" />
                <el-option label="JavaScript" value="js" />
                <el-option label="CSS" value="css" />
                <el-option label="HTML" value="html" />
                <el-option label="JSON" value="json" />
                <el-option label="Markdown" value="md" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="时间范围">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                @change="handleDateRangeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="文件大小">
              <div class="size-range">
                <el-input-number
                  v-model="sizeMin"
                  placeholder="最小"
                  :min="0"
                  size="small"
                  @change="handleSizeRangeChange"
                />
                <span class="size-separator">-</span>
                <el-input-number
                  v-model="sizeMax"
                  placeholder="最大"
                  :min="0"
                  size="small"
                  @change="handleSizeRangeChange"
                />
                <el-select v-model="sizeUnit" size="small" style="width: 60px">
                  <el-option label="B" value="1" />
                  <el-option label="KB" value="1024" />
                  <el-option label="MB" value="1048576" />
                </el-select>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <!-- 版本过滤 -->
      <div class="filter-section">
        <h4>版本过滤</h4>
        <el-form-item label="选择版本">
          <el-select
            v-model="selectedVersions"
            multiple
            placeholder="选择要搜索的版本（空表示全部）"
            style="width: 100%"
            @change="handleVersionsChange"
          >
            <el-option
              v-for="version in availableVersions"
              :key="version.id"
              :label="`${version.id} (${formatTimestamp(version.timestamp)})`"
              :value="version.id"
            />
          </el-select>
        </el-form-item>
      </div>

      <!-- 文件类型过滤 -->
      <div class="filter-section">
        <h4>文件类型过滤</h4>
        <el-form-item label="文件扩展名">
          <el-select
            v-model="selectedFileTypes"
            multiple
            placeholder="选择文件类型（空表示全部）"
            style="width: 100%"
            @change="handleFileTypesChange"
          >
            <el-option
              v-for="fileType in commonFileTypes"
              :key="fileType.value"
              :label="fileType.label"
              :value="fileType.value"
            />
          </el-select>
        </el-form-item>
      </div>

      <!-- 操作按钮 -->
      <div class="filter-actions">
        <el-button @click="resetFilters">重置过滤器</el-button>
        <el-button type="primary" @click="applyFilters">应用过滤器</el-button>
      </div>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, reactive } from 'vue'
import type { 
  SearchOptions, 
  ContentSearchOptions, 
  SearchCriteria, 
  HistoryVersion,

} from '../types/basic'

interface Props {
  options: SearchOptions
  contentOptions: ContentSearchOptions
  advancedCriteria: SearchCriteria
  searchType: 'filename' | 'content' | 'advanced'
  availableVersions: HistoryVersion[]
}

interface Emits {
  (e: 'update:options', value: SearchOptions): void
  (e: 'update:contentOptions', value: ContentSearchOptions): void
  (e: 'update:advancedCriteria', value: SearchCriteria): void
  (e: 'filterChange'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 本地状态
const localOptions = ref<SearchOptions>({ ...props.options })
const localContentOptions = ref<ContentSearchOptions>({ ...props.contentOptions })
const localAdvancedCriteria = ref<SearchCriteria>({ ...props.advancedCriteria })

const selectedVersions = ref<string[]>([])
const selectedFileTypes = ref<string[]>([])
const dateRange = ref<[string, string] | null>(null)
const sizeMin = ref<number | null>(null)
const sizeMax = ref<number | null>(null)
const sizeUnit = ref('1024') // KB by default

// 表单数据
const filterForm = reactive({})

// 常见文件类型
const commonFileTypes = [
  { label: 'Vue 组件 (*.vue)', value: 'vue' },
  { label: 'TypeScript (*.ts)', value: 'ts' },
  { label: 'JavaScript (*.js)', value: 'js' },
  { label: 'CSS 样式 (*.css)', value: 'css' },
  { label: 'SCSS 样式 (*.scss)', value: 'scss' },
  { label: 'HTML 文档 (*.html)', value: 'html' },
  { label: 'JSON 数据 (*.json)', value: 'json' },
  { label: 'Markdown (*.md)', value: 'md' },
  { label: '配置文件 (*.config.*)', value: 'config' }
]

// 监听 props 变化
watch(() => props.options, (newOptions) => {
  localOptions.value = { ...newOptions }
  selectedVersions.value = newOptions.versionIds || []
  selectedFileTypes.value = newOptions.fileTypes || []
}, { deep: true })

watch(() => props.contentOptions, (newOptions) => {
  localContentOptions.value = { ...newOptions }
}, { deep: true })

watch(() => props.advancedCriteria, (newCriteria) => {
  localAdvancedCriteria.value = { ...newCriteria }
  
  // 同步日期范围
  if (newCriteria.dateRange) {
    dateRange.value = [
      newCriteria.dateRange.start.toISOString(),
      newCriteria.dateRange.end.toISOString()
    ]
  } else {
    dateRange.value = null
  }
  
  // 同步大小范围
  if (newCriteria.sizeRange) {
    sizeMin.value = newCriteria.sizeRange.min
    sizeMax.value = newCriteria.sizeRange.max
  } else {
    sizeMin.value = null
    sizeMax.value = null
  }
}, { deep: true })

// 处理基础选项变化
function handleOptionsChange() {
  localOptions.value.versionIds = selectedVersions.value
  localOptions.value.fileTypes = selectedFileTypes.value
  emit('update:options', { ...localOptions.value })
  emit('filterChange')
}

// 处理内容搜索选项变化
function handleContentOptionsChange() {
  // 同步基础选项
  Object.assign(localContentOptions.value, localOptions.value)
  emit('update:contentOptions', { ...localContentOptions.value })
  emit('filterChange')
}

// 处理高级搜索条件变化
function handleAdvancedCriteriaChange() {
  emit('update:advancedCriteria', { ...localAdvancedCriteria.value })
  emit('filterChange')
}

// 处理版本选择变化
function handleVersionsChange() {
  localOptions.value.versionIds = selectedVersions.value
  localContentOptions.value.versionIds = selectedVersions.value
  localAdvancedCriteria.value.versionIds = selectedVersions.value
  
  handleOptionsChange()
}

// 处理文件类型变化
function handleFileTypesChange() {
  localOptions.value.fileTypes = selectedFileTypes.value
  localContentOptions.value.fileTypes = selectedFileTypes.value
  
  handleOptionsChange()
}

// 处理日期范围变化
function handleDateRangeChange() {
  if (dateRange.value && dateRange.value.length === 2) {
    localAdvancedCriteria.value.dateRange = {
      start: new Date(dateRange.value[0]),
      end: new Date(dateRange.value[1])
    }
  } else {
    localAdvancedCriteria.value.dateRange = undefined
  }
  
  handleAdvancedCriteriaChange()
}

// 处理大小范围变化
function handleSizeRangeChange() {
  if (sizeMin.value !== null && sizeMax.value !== null) {
    const multiplier = parseInt(sizeUnit.value)
    localAdvancedCriteria.value.sizeRange = {
      min: sizeMin.value * multiplier,
      max: sizeMax.value * multiplier
    }
  } else {
    localAdvancedCriteria.value.sizeRange = undefined
  }
  
  handleAdvancedCriteriaChange()
}

// 重置过滤器
function resetFilters() {
  // 重置基础选项
  localOptions.value = {
    caseSensitive: false,
    exactMatch: false,
    fileTypes: [],
    versionIds: [],
    maxResults: 1000
  }
  
  // 重置内容搜索选项
  localContentOptions.value = {
    ...localOptions.value,
    contextLines: 2,
    regex: false
  }
  
  // 重置高级搜索条件
  localAdvancedCriteria.value = {
    fileName: '',
    content: '',
    fileType: '',
    dateRange: undefined,
    sizeRange: undefined,
    versionIds: []
  }
  
  // 重置 UI 状态
  selectedVersions.value = []
  selectedFileTypes.value = []
  dateRange.value = null
  sizeMin.value = null
  sizeMax.value = null
  
  // 触发更新
  emit('update:options', { ...localOptions.value })
  emit('update:contentOptions', { ...localContentOptions.value })
  emit('update:advancedCriteria', { ...localAdvancedCriteria.value })
  emit('filterChange')
}

// 应用过滤器
function applyFilters() {
  emit('filterChange')
}

// 格式化时间戳
function formatTimestamp(timestamp: number): string {
  return new Date(timestamp).toLocaleString('zh-CN')
}
</script>

<style scoped>
.search-filters {
  width: 100%;
}

.filter-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.filter-section:last-of-type {
  border-bottom: none;
}

.filter-section h4 {
  margin: 0 0 16px 0;
  color: var(--el-text-color-primary);
  font-size: 14px;
  font-weight: 600;
}

.size-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.size-separator {
  color: var(--el-text-color-regular);
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
  border-top: 1px solid var(--el-border-color-lighter);
}
</style>